package com.googlecode.mylyn.core.util;

import org.apache.commons.lang.StringUtils;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.mylyn.commons.net.AuthenticationCredentials;
import org.eclipse.mylyn.commons.net.AuthenticationType;
import org.eclipse.mylyn.tasks.core.RepositoryStatus;
import org.eclipse.mylyn.tasks.core.TaskRepository;

import com.googlecode.mylyn.core.GoogleCodeCorePlugin;

/**
 * Utility methods for dealing with {@link TaskRepository}.
 */
public final class RepositoryUtils {

    private RepositoryUtils() {
        throw new AssertionError("not instantiable");
    }

    public static boolean isLoggedIn(TaskRepository repository) {
        if (StringUtils.isEmpty(repository.getUserName())) {
            return false;
        }
        AuthenticationCredentials credentials = repository.getCredentials(AuthenticationType.REPOSITORY);
        return credentials != null && !StringUtils.isEmpty(credentials.getPassword());
    }

    public static boolean isAnonymous(TaskRepository repository) {
        return (repository.getCredentials(AuthenticationType.REPOSITORY) == null);
    }

    public static void assertLoggedIn(TaskRepository repository) throws CoreException {
        if (!isLoggedIn(repository)) {
            throw new CoreException(new RepositoryStatus(
                    repository,
                    IStatus.ERROR,
                    GoogleCodeCorePlugin.PLUGIN_ID,
                    RepositoryStatus.ERROR_REPOSITORY_LOGIN,
                     "not logged in"));
        }
    }

}
